package com.hoperun.controller.admin;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hoperun.bean.AdminManager;
import com.hoperun.bean.AdminPermissions;
import com.hoperun.controller.common.BaseController;
import com.hoperun.framework.ex.XHZException;
import com.hoperun.framework.ibatis.page.BootGrid;
import com.hoperun.framework.ibatis.page.BootGridPage;
import com.hoperun.framework.models.DataView;
import com.hoperun.framework.query.Criteria;
import com.hoperun.framework.util.Constant;
import com.hoperun.framework.util.DateUtils;
import com.hoperun.service.IAdminManagerSV;
import com.hoperun.service.IAdminPermissionsSV;
import com.hoperun.utils.ErrorCode;
import com.hoperun.utils.Constant.RecordState;

/**
 * Copyright: Copyright (c) 2016 GUO~AN <br/>
 * ClassName: AdminPermissionsController.java
 * 
 * @Description:
 * 
 * @version: v1.0.0
 * @author: fuyu
 * @date: 2016-1-8 上午9:11:06
 * 
 *        Modification History: Date Author Version Description
 *        ---------------------------------------------------------* 2016-1-8
 *        fuyu v1.0.0 修改理由
 */
@Controller
@RequestMapping("/admin/admin/permissions")
@RequiresUser
public class AdminPermissionsController extends BaseController {

	@Resource
	private IAdminPermissionsSV adminPermissionsSV;
	@Resource
	private IAdminManagerSV adminManagerSV;

	@ModelAttribute
	public void populateModel(final HttpServletRequest request,
			ModelMap modelMap) {
		try {
			super.initMenus(request, modelMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/{menu}/{menuNext}")
	public String index(@PathVariable long menu, @PathVariable long menuNext,
			ModelMap modelMap) {

		modelMap.put("menuType", menu);
		modelMap.put("menuNextType", menuNext);

		return "admin:adminpermissions.list";
	}

	@RequestMapping("/tree")
	@ResponseBody
	public DataView organizationTree(
			@RequestParam(value = "permId", defaultValue = "0") Long pid) {

		Criteria criteria = new Criteria();
		DataView dataView = new DataView();
		try {
			if (null == pid || pid < 1) {
				criteria.addNull(AdminPermissions.COL_PARENT_PERM_ID,
						Criteria.AND);
			} else {
				criteria.addEqual(AdminPermissions.COL_PARENT_PERM_ID, pid,
						Criteria.AND);
			}
			criteria.addEqual(AdminPermissions.COL_STATUS, RecordState.STS_USE,
					Criteria.AND);
			criteria.orderBy(AdminPermissions.COL_SORT + " DESC ");
			List<AdminPermissions> list = adminPermissionsSV
					.queryByCondition(criteria);
			if (CollectionUtils.isNotEmpty(list)) {
				dataView.setCode(Constant.SUCCESS);
				dataView.setData(list);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return dataView;
	}

	@RequestMapping("/page")
	@ResponseBody
	public BootGridPage<AdminPermissions> identityUserPage(
			BootGrid<AdminPermissions> grid, AdminPermissions adminPermissions,
			ModelMap modelMap) {
		BootGridPage<AdminPermissions> pageModel = new BootGridPage<AdminPermissions>();

		try {
			Criteria criteria = new Criteria();

			if (null == grid)
				return new BootGridPage<AdminPermissions>();
			String perName = grid.getSearchPhrase();
			if (StringUtils.isNotBlank(perName)) {
				criteria.addLike(AdminPermissions.COL_PERM_NAME, "%" + perName
						+ "%", Criteria.AND);
			}

			criteria.orderBy(AdminPermissions.COL_SORT);
			criteria.addEqual(AdminPermissions.COL_STATUS, RecordState.STS_USE,
					Criteria.AND);
			pageModel = adminPermissionsSV.queryPage(criteria, grid);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return pageModel;
	}

	@RequestMapping("/create")
	public String create(AdminPermissions adminPermissions, ModelMap modelMap) {
		try {
			modelMap.addAttribute("method", "save");
			Criteria criteria = new Criteria();
			criteria.addEqual(AdminPermissions.COL_PARENT_PERM_ID,
					adminPermissions.getParentPermId(), Criteria.AND);
			criteria.addEqual(AdminPermissions.COL_STATUS, RecordState.STS_USE,
					Criteria.AND);
			criteria.orderBy(AdminPermissions.COL_SORT + " DESC ");
			criteria.limit(Constant.ZERO, Constant.ONE);
			List<AdminPermissions> aps = adminPermissionsSV
					.queryByCondition(criteria);
			if (CollectionUtils.isEmpty(aps)) {
				adminPermissions.setSort(Constant.ONE);
			} else {
				adminPermissions.setSort(Constant.ONE
						+ aps.get(Constant.ZERO).getSort());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		modelMap.addAttribute("row", adminPermissions);
		return "adminAlone:adminpermissions.info";
	}

	@RequestMapping("/modify/{id}")
	public String modify(@PathVariable Long id, ModelMap modelMap,
			final HttpServletRequest request) {
		AdminPermissions adminPermissions = null;
		try {
			adminPermissions = adminPermissionsSV.queryById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		modelMap.addAttribute("method", "update");
		modelMap.addAttribute("row", adminPermissions);
		return "adminAlone:adminpermissions.info";
	}

	@RequestMapping("/detail/{id}")
	public String detail(@PathVariable Long id, ModelMap modelMap,
			final HttpServletRequest request) {
		AdminPermissions adminPermissions = null;
		try {
			adminPermissions = adminPermissionsSV.queryById(id);
			adminPermissions.setCreateStrTime(DateUtils
					.dateString(adminPermissions.getCreatime()));
			if (null != adminPermissions.getUpdatetime()) {
				adminPermissions.setUpdateStrTime(DateUtils
						.dateString(adminPermissions.getUpdatetime()));
			}
			AdminManager am = adminManagerSV.queryById(adminPermissions
					.getCreator());
			adminPermissions.setStrCreator(am.getRealName());
			if (StringUtils.isNotBlank("" + adminPermissions.getUpdator())) {
				am = adminManagerSV.queryById(adminPermissions.getUpdator());
				adminPermissions.setStrUpdator(am.getRealName());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		modelMap.addAttribute("row", adminPermissions);
		return "adminAlone:adminpermissions.detail";
	}

	@RequestMapping("/save")
	@ResponseBody
	public DataView save(AdminPermissions adminPermissions) {
		DataView dataView = new DataView();

		try {
			adminPermissionsSV.save(adminPermissions);

			dataView.setCode(Constant.SUCCESS);
			dataView.setMessage("新增成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dataView;
	}

	@RequestMapping("/update")
	@ResponseBody
	public DataView update(AdminPermissions adminPermissions) {
		DataView dataView = new DataView();

		if (null == adminPermissions
				|| StringUtils.isBlank("" + adminPermissions.getPermId())) {
			throw new XHZException(ErrorCode.MISS_PARAM, null,
					new Object[] { "id信息" });
		}

		try {
			adminPermissionsSV.update(adminPermissions);

			dataView.setCode(Constant.SUCCESS);
			dataView.setMessage("修改成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dataView;
	}

	@RequestMapping("/find/{id}")
	@ResponseBody
	public AdminPermissions findOne(@PathVariable Long id) {
		AdminPermissions adminPermissions = null;
		try {
			adminPermissions = adminPermissionsSV.queryById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return adminPermissions;
	}

	@RequestMapping("/delete")
	@ResponseBody
	public DataView delete(Long id) {
		DataView dataView = new DataView();
		try {
			adminPermissionsSV.delete(id);
			dataView.setCode(Constant.SUCCESS);
			dataView.setMessage("操作成功");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return dataView;
	}
}
